package com.roc.util.httpZip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.roc.util.Constance;

/**
 * 
 * @ClassName: HttpFileToZipUtil
 * @Description: TODO
 * @author jdd
 * @date 2017年2月19日
 * 
 */
public abstract class HttpFileToZipUtil {

	/**
	 * 远程文件打包
	 * 
	 * @Title: httpFileToZip
	 * @Description: TODO
	 * @param @param zipFilePath
	 * @param @param fileName
	 * @param @param map key 图片名称 value  url
	 * @param @return    
	 * @return boolean    
	 * @throws
	 * @author jdd
	 */
	public static boolean httpFileToZip(String zipFilePath, String fileName, Map<String,String> map)
	{
		File zipFile = new File(zipFilePath , fileName + ".zip");
		if (!zipFile.getParentFile().exists())
			zipFile.getParentFile().mkdirs();
		boolean falg=false;
		try {
			falg = fileToZip(new FileOutputStream(zipFile), map);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return falg;
	}
	/**
	 * 远程文件打包
	 * @Title: httpFileToZip
	 * @Description: TODO
	 * @param @param zipFilePath
	 * @param @param fileName
	 * @param @param httpUrls
	 * @param @return    
	 * @return boolean    
	 * @throws
	 * @author jdd
	 */
	public static boolean httpFileToZip(String zipFilePath, String fileName, Object... httpUrls)
	{
		//图片名称不能重复
		Map<String,String> map = new HashMap<String,String>();
		boolean falg=false;
		for (Object url : httpUrls) {
			String resName=getFileName((String)url);
			map.put(resName, (String)url);
		}
		File zipFile = new File(zipFilePath , fileName + ".zip");
		if (!zipFile.getParentFile().exists())
			zipFile.getParentFile().mkdirs();
		
		try {
			falg = fileToZip(new FileOutputStream(zipFile), map);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return falg;
	}
	/**
	 * 截取图片名称
	 */
	protected static String getFileName(String httpUrl)
	{
		String sub = httpUrl.substring(httpUrl.lastIndexOf("mid=")+4, httpUrl.length());
		return sub.substring(0,sub.indexOf("&"));
	}
	/**
	 * 获取远程图片的输入流
	 * @Title: getInputStream
	 * @Description: TODO
	 * @param @param httpUrl
	 * @param @return    
	 * @return InputStream    
	 * @throws
	 * @author jdd
	 */
	protected static InputStream getInputStream(String httpUrl)
	{
		InputStream is = null;  
        try {  
            URL urlGet = new URL(httpUrl);  
            HttpURLConnection http = (HttpURLConnection) urlGet  
                    .openConnection();  
            http.setRequestMethod("GET"); // 必须是get方式请求  
            http.setRequestProperty("Content-Type",  
                    "application/x-www-form-urlencoded");  
            http.setDoOutput(true);  
            http.setDoInput(true);  
            System.setProperty("sun.net.client.defaultConnectTimeout", "60000");// 连接超时30秒  
            System.setProperty("sun.net.client.defaultReadTimeout", "60000"); // 读取超时30秒  
            http.connect();  
            // 获取文件转化为byte流  
            is = http.getInputStream();  
  
        } catch (Exception e) {  
            e.printStackTrace();  
            throw new RuntimeException("获取远程图片失败：url="+httpUrl);
        }  
        return is;  
	}

	protected static boolean fileToZip(FileOutputStream outputStream,Map<String,String> map) {
		InputStream fis = null;
		BufferedInputStream bis =null;
		ZipOutputStream	zos = null;
		try {
			zos = new ZipOutputStream(new BufferedOutputStream(outputStream));
			byte[] bufs = new byte[1024 * 10];
			Set<String> fileNames = map.keySet();
			Iterator<String> fileNamesIter = fileNames.iterator();
			while(fileNamesIter.hasNext())
			{
				String key=fileNamesIter.next();
				ZipEntry zipEntry = new ZipEntry(key);
				zos.putNextEntry(zipEntry);
				String value=map.get(key);
				fis = getInputStream(value);
				bis = new BufferedInputStream(fis, 1024 * 10);
				int read = 0;
				while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
					zos.write(bufs, 0, read);
				}
				fis.close();
				bis.close();
			}
				// 读取待压缩的文件并写进压缩包里
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally {
			// 关闭流
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
				if (null != fis)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return true;
	}
	
	 /**
	   * 删除某个文件夹下的所有文件夹和文件
	   */
	  
	  
	  public static boolean deletefile(String delpath)
	          throws FileNotFoundException, IOException {
	      try {

	          File file = new File(delpath);
	          if (!file.isDirectory()) {

	              file.delete();
	          } else if (file.isDirectory()) {

	              String[] filelist = file.list();
	              for (int i = 0; i < filelist.length; i++) {
	                  File delfile = new File(delpath + File.separator + filelist[i]);
	                  if (!delfile.isDirectory()) {
	                      delfile.delete();
	                  } else if (delfile.isDirectory()) {
	                      deletefile(delpath + File.separator + filelist[i]);
	                  }
	              }
	              file.delete();

	          }

	      } catch (FileNotFoundException e) {
	           e.getMessage();
	      }
	      return true;
	  }
	
	public static void main(String[] args) {
		Map<String,String> urlmap = new HashMap<String,String>();
		urlmap.put("85029004458000002001.jpg", "http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs=48502000&mid=85029004458000002001.jpg&time=1488158611520");
		urlmap.put("17022317003282607001.jpg", "http://localhost:8080/fmposm/upload/showImg.ct?orgs=85278888&mid=17022317003282607001.jpg&time=1487840529436");
		urlmap.put("bg_hd_nav.jpg", "http://localhost:8080/fmposm/images/bg_hd_nav.jpg");
		urlmap.put("bg_header.jpg", "http://localhost:8080/fmposm/images/bg_header.jpg");
		String zipFilePath = "C:\\upload\\file\\zip";//压缩包存放的文件夹
		String zipName="商户图片"+Constance.formateDate();
		HttpFileToZipUtil.httpFileToZip(zipFilePath, zipName,urlmap);
		List<String> urlList = new ArrayList<String>();
		urlList.add("http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs=48502000&mid=85029004458000002001.jpg&time=1488158611520");
		HttpFileToZipUtil.httpFileToZip(zipFilePath, zipName+"1", urlList.toArray());
	}
}
